#include "cjson.h"

#include <sstream>

#include "log.h"

namespace chat {
bool JsonUtil::serialize(const Json::Value& root, std::string* body) {
    if (!body) {
        LOG_ERROR("body 为 null");
        return false;
    }

    try {
        Json::StreamWriterBuilder builder;
        // 配置不转义非ASCII字符（关键设置）
        builder.settings_["emitUTF8"] = true;
        builder.settings_["indentation"] = "";  // 无缩进，压缩输出
        builder["encoding"] = "UTF-8";

        *body = Json::writeString(builder, root);
        return true;

    } catch (const std::exception& e) {
        LOG_ERROR("序列化异常: {}", e.what());
        return false;
    }
}

bool JsonUtil::unSerialize(Json::Value* root, const std::string& body) {
    if (!root) {
        LOG_ERROR("root 为 null");
        return false;
    }

    try {
        Json::CharReaderBuilder readerBuilder;
        // 配置支持UTF-8编码（关键设置）
        readerBuilder["collectComments"] = false;

        std::string errors;
        std::istringstream stream(body);
        const bool success =
            Json::parseFromStream(readerBuilder, stream, root, &errors);

        if (!success) {
            LOG_ERROR("反序列化失败: {}", errors);
            return false;
        }

        return true;

    } catch (const std::exception& e) {
        LOG_ERROR("反序列化异常: {}", e.what());
        return false;
    }
}
}   // namespace chat